import { _decorator, Button, Component, director, Node, ProgressBar, resources, Socket } from 'cc';
import { http } from '../script/common/HTTP';
import { socket } from '../script/common/socket';
import CryptoJS from 'crypto-js'; // 引入crypto-js库
import { userinfo } from '../script/UserInfo';

import { Utils } from '../script/utils/Utils';
import protocol from '../proto/protoExt';
const { ccclass, property } = _decorator;

@ccclass('boot')
export class boot extends Component {

    @property(ProgressBar)
    progressbar: ProgressBar = null!;

    @property(Node)
    startbtn: Node = null!;


    start() {
        this.startbtn.active = false;

        resources.loadDir("/",
            (finished: number, total: number) => {
                this.progressbar.progress = finished / total;
            },
            () => {
                this.progressbar.node.active = false;
                this.startbtn.active = true;
            })

        this.startbtn.on("click", async () => {
            let data = {
                account: "insulate",
                password: CryptoJS.MD5("123456").toString(),
                auth_type: 0
            }

            http.requestAsync("POST", "v0/auth", data)
                .then(res => {
                    if (!res) return;
                    http.setToken(res.access_token);
                    http.setUid(res.uid);

                    socket.connect(res.uid, res.access_token, async () => {
                        let fishs: protocol.new_world.v1.FishListResult = await http.requestAsync("POST", "v1/fish/list").catch(() => { console.log("获取鱼列表失败") })
                        userinfo.setFishs(fishs.list)
                        director.loadScene("lobby")
                    })
                    return http.requestAsync("POST", "v1/system/configs");
                })
                .catch(error => {
                    console.log("登录失败", error);
                })
                .then(configs => {
                    if (!configs) return;
                    Utils.setConfigs(configs);
                    return http.requestAsync("POST", "v1/system/now");
                })
                .catch(error => {
                    console.log("获取配置失败", error);
                })
                .then(nowms => {
                    if (!nowms) return;
                    Utils.setServerTime(nowms.now_ms)

                })
                .catch(error => {
                    console.log("请求失败", error);
                });



        })
    }

    update(deltaTime: number) {

    }
}


